/*GLOBAL VARIABLES*/
var blankString = /^\s*$/;
var graphsData = null;
var weekLabels = [ "E", "T", "K", "N", "R", "L", "P" ];

function setPeriodDatePickers() {
	$("#periodFrom").datepicker();
	$("#periodFrom").datepicker("option", "dateFormat", "dd.mm.yy");
	$("#periodTo").datepicker();
	$("#periodTo").datepicker("option", "dateFormat", "dd.mm.yy");
}

function getGraphs() {
	if (!neededValuesExist()) {
		return;
	}
	getGraphsData();
	if (graphsData == null) {
		setInfoMessage("Andmeid ei leitud");
		return;
	}

	// Show answered day count of course results of specified student
	// if course was not specified or no concrete student was given, then show nothhing
	var dayCountData = graphsData.dayCountData;
	if (dayCountData != null) {
		document.getElementById("dayCount").innerHTML = dayCountData;
	}

	// Show hour sum spent on studying of specified
	// course or all courses in given period
	var hourCountData = graphsData.hourCountData;
	if (hourCountData != null) {
		document.getElementById("hourCount").innerHTML = hourCountData;
	}

	// Construct week graph
	constructWeekGraph();

	// If method was chosen, then do not show method's pie chart
	var methodsData = graphsData.methodGraphData;
	if (exists(methodsData)) {
		constructPieChart();
	} else {
		clearGraph('pieChart');
	}
	// constructLineGraph();
}

function exists(array) {
	return array != undefined && array.length > 0;
}

// Get data for graphs from DB
function getGraphsData() {
	$.ajax({
		async : false,
		type : "POST",
		data : {
			"periodFrom" : getValue("periodFrom"),
			"periodTo" : getValue("periodTo"),
			"courseCode" : getValue("courseCode"),
			"studentCode" : getValue("studentCode"),
			"group" : getValue("groupType"),
			"methodId" : getValue("method")
		},
		dataType : "text",
		url : "GraphData"
	}).success(function(response) {
		graphsData = jQuery.parseJSON(response);
	});
}

function clearGraph(id) {
	var canvas = document.getElementById(id);
	canvas.width = canvas.width;
	RGraph.ObjectRegistry.Clear(canvas);
}

// Function for designing weekGraph -
// bar graph of student's average studying hours in each weekday
function constructWeekGraph() {
	clearGraph('weekGraphBar');
	var weekBar = new RGraph.Bar('weekGraphBar', graphsData.weekGraphData);
	weekBar.Set('chart.labels', weekLabels);
	RGraph.Effects.Bar.Grow(weekBar);
}

// Function for designing learning methods' pie chart -
// pie chart of percentage value of used learning methods -
// here we can see which learning methods were used more/less to learn one specified course or all courses
function constructPieChart() {
	clearGraph('pieChart');
	var data = graphsData.methodGraphData;
	var pie = new RGraph.Pie('pieChart', data[0].methodPercents);
	pie.Set('chart.key', data[1].methodTypes);
	pie.Set('chart.tooltips', data[1].methodTypes);
	pie.Set('chart.tooltips.event', 'onmousemove');
	pie.Set('chart.strokestyle', 'white');
	pie.Set('chart.linewidth', 3);
	pie.Set('chart.shadow', true);
	pie.Set('chart.shadow.offsetx', 2);
	pie.Set('chart.shadow.offsety', 2);
	pie.Set('chart.shadow.blur', 3);
	pie.Set('chart.exploded', 7);
	pie.Draw();
	RGraph.Effects.Fade.In(pie, {
		'frames' : 10,
		'duration' : 1000
	});
}

function constructLineGraph() {
	var line = new RGraph.Line('cvs', [ 4, 5, 1, 6, 3, 5, 2 ], [ 7, 7, 8, 6, 2, 1, 1 ]);
	line.Set('chart.curvy', true);
	line.Set('chart.curvy.tickmarks', true);
	line.Set('chart.curvy.tickmarks.fill', null);
	line.Set('chart.curvy.tickmarks.stroke', '#aaa');
	line.Set('chart.curvy.tickmarks.stroke.linewidth', 2);
	line.Set('chart.curvy.tickmarks.size', 5);
	line.Set('chart.linewidth', 3);
	line.Set('chart.hmargin', 5);
	line.Set('chart.labels', [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]);
	line.Set('chart.tooltips', [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]);
	line.Set('chart.tickmarks', 'circle');
	RGraph.Effects.Line.jQuery.Trace(line);
}

/** FUNCTIONS FOR CRITERIA INPUT VALIDATING * */
// Function to get value of element with given id
function getValue(id) {
	return document.getElementById(id).value;
}

// Function for controlling if value of element with given id is not empty
function valueExists(id) {
	return getValue(id).match(blankString) == null;
}

// Insert error message for user
function setErrorMessage(message) {
	document.getElementById("message").style.color = "red";
	document.getElementById("message").innerHTML = message;
}
// Insert info message for user
function setInfoMessage(message) {
	document.getElementById("message").style.color = "blue";
	document.getElementById("message").innerHTML = message;
}

function neededValuesExist() {
	// 'period-' must always exist; if only one side exists - count as one day
	if (!valueExists("periodFrom") && !valueExists("periodTo")) {
		setErrorMessage("Väli 'Periood' on kohustuslik!");
		return false;
	}
	// 'periodTo' must be after 'periodFrom'
	if (valueExists("periodFrom") && valueExists("periodTo") && !endDateAfterStartDate()) {
		return false;
	}
	// 'studentCode' and 'group' cannot be given at same time
	if (valueExists("studentCode") && valueExists("groupType")) {
		setErrorMessage("Palun sisestage tudengi kood VÕI grupp, mitte mõlemad!");
		return false;
	}
	// If 'group' is given, the 'course' must be specified too
	// in order not to overload the graphs
	if (valueExists("groupType") && !valueExists("courseCode")) {
		setErrorMessage("Gruppi valimisel palun täpsustage aine ka!");
		return false;
	}
	setInfoMessage("Otsin...");
	return true;
}

function endDateAfterStartDate() {
	var start = $("#periodFrom")[0].value;
	var end = $("#periodTo")[0].value;
	var startDate = start.split(".");
	var endDate = end.split(".");

	// Controls that appropriate date is inserted (dd.MM.yyyy)
	if (startDate.length < 3 || endDate.length < 3 || startDate[2].length < 4 || endDate[2].length < 4) {
		setErrorMessage("Algus- või lõppkuupäev on vales formaadis! Õige formaat on pp.kk.aaaa");
		return false;
	}

	if (parseInt(startDate[2], 10) > parseInt(endDate[2], 10)) {
		setWrongDatesErrorMessage();
		return false;
	}
	if (parseInt(startDate[2], 10) == parseInt(endDate[2], 10)) {
		if (parseInt(startDate[1], 10) > parseInt(endDate[1], 10)) {
			setWrongDatesErrorMessage();
			return false;
		}
		if (parseInt(startDate[1], 10) == parseInt(endDate[1], 10) && parseInt(startDate[0], 10) > parseInt(endDate[0], 10)) {
			setWrongDatesErrorMessage();
			return false;
		}
	}
	return true;
}

function setWrongDatesErrorMessage() {
	setErrorMessage("Lõppkuupäev ei saa olla varem kui alguskuupäev!");
}
